//
//  VRAddUserGroupViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/19.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRAddUserGroupViewController.h"

@interface VRAddUserGroupViewController () <UITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray<UIView *> *inputViewArray;

@end

@implementation VRAddUserGroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ScrollViewBgColor;
    self.title = @"添加用户组";
    
    self.inputViewArray = [NSMutableArray array];
    
    [self setupSubView];
}

- (void)setupSubView {
    
    UIView *contentView = [[UIView alloc] init];
    [self.view addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(NAVIGATION_BAR_HEIGHT + 30);
        make.width.mas_equalTo(kScreenWidth);
        //        make.height.mas_equalTo(200);
    }];
    
    
    NSArray *titleArray = @[@"用户名称：", @"联系方式："];
    NSArray *placeholderArray = @[@"输入用户名称", @"输入联系方式"];
    for (int i = 0; i < titleArray.count; i++) {
        
        UIView *inputView = [[UIView alloc] init];
        inputView.layer.borderColor = RGB(180, 180, 180).CGColor;
        inputView.layer.borderWidth = 1.0;
        inputView.size = CGSizeMake(kScreenWidth - 40, 44);
        [contentView addSubview:inputView];
        
        UILabel *titleLbl = [[UILabel alloc] init];
        titleLbl.text = titleArray[i];
        titleLbl.textColor = RGB(80, 80, 80);
        titleLbl.font = VRFont(14);
        titleLbl.frame = CGRectMake(15, 0, 72, 44);
        [inputView addSubview:titleLbl];
        
        UITextField *tf = [[UITextField alloc] init];
        tf.tag = 1001;
        tf.font = VRFont(16);
        tf.textColor = RGB(51, 51, 51);
        [tf setValue:RGB(107, 198, 255) forKeyPath:@"_placeholderLabel.textColor"];
        tf.placeholder = placeholderArray[i];
        tf.frame = CGRectMake(CGRectGetMaxX(titleLbl.frame) + 10, 0, kScreenWidth - CGRectGetMaxX(titleLbl.frame) - 40 - 10, 44);
        tf.delegate = self;
        [tf addTarget:self action:@selector(textFieldTextChanged:) forControlEvents:UIControlEventEditingChanged];
        [inputView addSubview:tf];
        
        tf.keyboardType = UIKeyboardTypeNumberPad;
        tf.clearButtonMode = UITextFieldViewModeWhileEditing;
        if (i == 0) {
            
            tf.keyboardType = UIKeyboardTypeDefault;
        }else if (i == 1) {
            
            tf.keyboardType = UIKeyboardTypeNumberPad;
        }
        
        CGFloat inputViewY = i * 44 + i * 15;
        inputView.frame = CGRectMake(20, inputViewY, kScreenWidth - 40, 44);
        [self.inputViewArray addObject:inputView];
    }
    
    
    [contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo([self.inputViewArray lastObject]);
    }];
    
    
    // 按钮
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.backgroundColor = RGB(78, 173, 57);
    loginBtn.layer.cornerRadius = 4;
    [loginBtn setTitle:@"完成添加" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = VRFont(16);
    [loginBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [loginBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [loginBtn addTarget:self action:@selector(onSaveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    //    self.loginBtn = loginBtn;
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(contentView.mas_bottom).offset(50);
        make.width.mas_equalTo(kScreenWidth - 40);
        make.height.mas_equalTo(46);
    }];
}


#pragma mark - networking
- (void)addUserGroup
{
    UITextField *tf0 = [self.inputViewArray[0] viewWithTag:1001];
    UITextField *tf1 = [self.inputViewArray[1] viewWithTag:1001];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userID"] = [VRUser shareUser].token;
    param[@"name"] = tf0.text;
    param[@"phone"] = tf1.text;
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:AddUserGroup parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [hud hideAnimated:YES];
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            });
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
    } error:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
        });
    }];
}


#pragma mark - action
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)onSaveBtnClick:(UIButton *)sender
{
    
    UITextField *tf0 = [self.inputViewArray[0] viewWithTag:1001];
    UITextField *tf1 = [self.inputViewArray[1] viewWithTag:1001];
    
    if (tf0.text.length == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"用户名不能为空"];
        return;
    }
    if ([NSString valiMobile:tf1.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    if (tf1.text.length == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"手机号不能为空"];
        return;
    }
    
    [self addUserGroup];
}

#pragma mark - delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    UITextField *tf = [self.inputViewArray[1] viewWithTag:1001];
    if ([string length] > 0) {
        if (textField == tf) {
            
            if (![self deptNumInputShouldNumber:string]) {
                return NO;
            }
            if (textField.text.length >= 11) {
                return NO;
            }
        } else {
            
            //            if (![self deptNumInputShouldNumber:string]) {
            //                return NO;
            //            }
            //            if (textField.text.length >= 6) {
            //                return NO;
            //            }
        }
    }
    return YES;
}


- (void)textFieldTextChanged:(UITextField *)textField
{
    
    UITextField *tf = [self.inputViewArray[0] viewWithTag:1001];
    if (textField == tf) {
        

    }else{
        
        //        if (textField.text.length == 6 && self.usernameTF.text.length == 11) {
        //
        //            self.loginBtn.enabled = YES;
        //        }else{
        //            self.loginBtn.enabled = NO;
        //        }
    }
}

- (BOOL)deptNumInputShouldNumber:(NSString *)str
{
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}



@end
